/**
 * 功能说明：Axios 实例与拦截器，包含基于 adapter 的本地 mock。
 */
import axios from 'axios'
import store from '../store'
import { CONFIG } from '../config'

const defaultAdapter = axios.defaults.adapter

const http = axios.create({ baseURL: CONFIG.BASE_URL, timeout: 10000 })

http.interceptors.request.use(
  (config) => {
    const token = store.getters['auth/isAuthenticated'] ? store.state.auth.token : null
    if (token) config.headers.Authorization = `Bearer ${token}`
    return config
  },
  (error) => { store.dispatch('error/handleError', error); return Promise.reject(error) }
)

http.interceptors.response.use(
  (res) => res.data,
  (error) => {
    const { response } = error
    const normalized = { message: response?.data?.message || error.message, status: response?.status || 0 }
    store.dispatch('error/handleError', normalized)
    return Promise.reject(normalized)
  }
)

if (CONFIG.USE_MOCK) {
  http.defaults.adapter = async function mockAdapter(config) {
    const url = config.url || ''; const method = (config.method || 'get').toLowerCase()
    const sleep = (ms) => new Promise(r => setTimeout(r, ms)); await sleep(200)

    // 登录
    if (url.startsWith('/auth/login') && method === 'post') {
      const { username, password } = config.data || {}
      if (username && password) return { data: { token: 'mock-' + Date.now(), user: { id: 1, name: username } }, status: 200, statusText: 'OK', headers: {}, config }
      return { data: { message: '用户名或密码错误' }, status: 401, statusText: 'Unauthorized', headers: {}, config }
    }

    // 注销
    if (url.startsWith('/auth/logout') && method === 'post') {
      return { data: { success: true }, status: 200, statusText: 'OK', headers: {}, config }
    }

    // 用户列表（分页）
    if (url.startsWith('/users') && method === 'get') {
      const page = parseInt(String((config.params && config.params.page) || '1'), 10)
      const pageSize = parseInt(String((config.params && config.params.pageSize) || String(CONFIG.PAGE_SIZE)), 10)
      const all = (window.__mockDB?.users || []).slice(); const total = all.length
      const start = (page - 1) * pageSize; const items = all.slice(start, start + pageSize)
      return { data: { items, total, page, pageSize }, status: 200, statusText: 'OK', headers: {}, config }
    }

    // 表单提交
    if (url.startsWith('/form/submit') && method === 'post') {
      const payload = config.data || {}
      if (!payload.name) return { data: { message: '名称为必填项' }, status: 422, statusText: 'Unprocessable Entity', headers: {}, config }
      return { data: { success: true, echo: payload }, status: 200, statusText: 'OK', headers: {}, config }
    }

    return defaultAdapter(config)
  }
}

export const get = (url, params = {}, config = {}) => http.get(url, { params, ...config })
export const post = (url, data = {}, config = {}) => http.post(url, data, config)
export const put = (url, data = {}, config = {}) => http.put(url, data, config)
export const del = (url, params = {}, config = {}) => http.delete(url, { params, ...config })

export default http

